package tragame.client;



import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import tragame.gui.JButton2;
import tragame.gui.JPanel2;
import tragame.game.Village;
import tragame.server.interfaces.IMap;

public class Client {
	
	public static String player;
	
	//Carte du server.
	public static IMap map;
	
	//Taille et coordonnée(coin supérieur gauche) courante de la carte.
	public static int map_size;
	public static int map_x;
	public static int map_y;
	
	//Case s�l�ctionn�e.
	public static Dimension selected;
	
	public static Dimension screenSize;
	
	public static JFrame frame, auth_window;
	public static JTextField login_field;
	public static JPanel2 main;
	public static JPanel map_view;
	public static JButton2 north,west,south,east;
	public static JTabbedPane options;
	public static JPanel infos, build_panel, milit_panel;
	public static JPanel2 infos_ressources;
	public static JLabel player_name, village_name, village_race,
						 res_food, res_wood, res_clay, res_iron;
	public static JLabel build_name, build_status, build_level;
	public static JComboBox build_list;
	public static JPanel build_pic;
	public static JButton2 upgrade_button, build_button;
	public static JLabel build_cost, upgrade_cost;
	public static JPanel2 build_infos, build_actions;
	
	public static Image background;
	
	public static String building_image;
	
	public static void sop(String s){
		System.out.println(s);
	}
	
	//Fonction qui simule une initialisation à la place du serveur.
	public static void initMap() throws RemoteException{
		
		map_size = 15;
		Registry reg = LocateRegistry.getRegistry(1099);
		
		
		try {
			map = (IMap) reg.lookup("/Map");
		} catch (NotBoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//map = Map.getInstance(map_size);
		map_x = 0;
		map_y = 0;
		selected = new Dimension(-1, -1);
		System.out.println("Ajout :");
		System.out.println(map.addVillage("Walrus", "Walland", Village.Race.gaulois, 5, 7));	
		System.out.println(map.addVillage("Latyr", "Latiland", Village.Race.germain, 1, 2));
		System.out.println(map.addVillage("Jing-Jing", "Jingoland", Village.Race.romain, 6, 3));
		
		//Autologin
		player = "Walrus";
	}	
	
	
	public static void main(String argv[])
	{
		frame = new JFrame("Tragame v0.1");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(new Dimension(1024,768));		
	
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			UIManager.put("TabbedPane.tabsOpaque", Boolean.FALSE);
			UIManager.put("TabbedPane.contentOpaque", Boolean.FALSE);
			Font corsiva = new Font(
					Font.createFont(
						Font.TRUETYPE_FONT, new FileInputStream(
								new File("Corsiva.ttf"))
						).getFamily(),
						Font.BOLD, 20
					);
			Font neverwinter = new Font(
					Font.createFont(
						Font.TRUETYPE_FONT, new FileInputStream(
								new File("Neverwinter.ttf"))
						).getFamily(),
						Font.BOLD, 14
					);
			UIManager.put("Label.font", neverwinter);
			UIManager.put("TitledBorder.font", corsiva);
		} 
		catch (ClassNotFoundException e) {}
		catch (InstantiationException e) {}
		catch (IllegalAccessException e) {}
		catch (UnsupportedLookAndFeelException e) {}
		catch (FileNotFoundException e) {}
		catch (FontFormatException e) {}
		catch (IOException e) {}
		
		screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		frame.setLocation(screenSize.width/2-1024/2, screenSize.height/2-768/2);
		
		background = Toolkit.getDefaultToolkit().getImage("background.jpg");		
		
		JMenuBar menu = new JMenuBar();
		
		JMenu file = new JMenu("Fichier");
		menu.add(file);
		
		JMenuItem login = new JMenuItem("Se connecter");
		login.addActionListener(
			new ActionListener() {
				public void actionPerformed(ActionEvent event){					
					
					auth_window = new JFrame("Fen�tre d'authentification");
					auth_window.setSize(new Dimension(300,200));
					auth_window.setLocation(screenSize.width/2-300/2, screenSize.height/2-200/2);
					
					JPanel2 auth_panel = new JPanel2("Y","C",300,200);
					auth_window.add(auth_panel);
					
					JPanel2 login_panel = new JPanel2("X","C",300,30);
					auth_panel.add(login_panel);
					
					JLabel login_label = new JLabel("Identifiant:");
					login_panel.add(login_label);
					
					login_field = new JTextField();
					login_panel.add(login_field);
					
					JPanel2 password_panel = new JPanel2("X","C",300,30);
					auth_panel.add(password_panel);
					
					JLabel password_label = new JLabel("Mot de passe:");
					password_panel.add(password_label);
					
					JTextField password_field = new JTextField();
					password_panel.add(password_field);
					
					JPanel2 validate_panel = new JPanel2("X","C",300,100);
					auth_panel.add(validate_panel);
					
					JButton2 accept = new JButton2(new ImageIcon("accept.gif"),
							 new ImageIcon("accept2.gif"),
							 125, 50);
					accept.addActionListener(
							new ActionListener() {
								public void actionPerformed(ActionEvent event){	
									
									//SI OK
									player = login_field.getText();
									frame.setTitle("Travian 1.0 - " + player);
									auth_window.dispose();
								}
							});
					validate_panel.add(accept);				
					
					JButton2 cancel = new JButton2(new ImageIcon("cancel.gif"),
							 new ImageIcon("cancel2.gif"),
							 125, 50);
					cancel.addActionListener(
							new ActionListener() {
								public void actionPerformed(ActionEvent event){	
									auth_window.dispose();
								}
							});
					validate_panel.add(cancel);					
										
					auth_window.setVisible(true);
				}
			}
		);
		file.add(login);
		
		JMenuItem register = new JMenuItem("Créer un compte");
		register.addActionListener(
			new ActionListener() {
				public void actionPerformed(ActionEvent event){
					System.exit(0);
				}
			}
		);
		file.add(register);
		
		JMenuItem exit = new JMenuItem("Quitter");
		exit.addActionListener(
			new ActionListener() {
				public void actionPerformed(ActionEvent event){
					System.exit(0);
				}
			}
		);
		file.add(exit);
		
		frame.setJMenuBar(menu);
		
		main = new JPanel2("X","C",1000,768){

			private static final long serialVersionUID = 1L;		
			
			public void paintComponent(Graphics g){
				super.paintComponent(g);
				g.drawImage(background,0,0,this);
			}
			
		};
		frame.getContentPane().add(main);
	
		JPanel map_panel = new JPanel(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		map_panel.setOpaque(false);
		main.add(map_panel);
		
		north = new JButton2(new ImageIcon("north.gif"), null, 105, 75);
		north.setEnabled(false);
		c.gridx = 1;
		c.gridy = 0;
		map_panel.add(north, c);
		north.addActionListener(new ActionListener(){

			public void actionPerformed(ActionEvent e) {
				
				//On v�rifie si on ne sors pas de la carte.package tragame.gui;
				if(map_y>0){
					map_y--;
					selected.height++;
					south.setEnabled(true);
				}
				
				//Si on arrive au bord de la carte, on d�sactive le bouton.
				if(map_y == 0) north.setEnabled(false);
				
				map_view.repaint();
			}
			
		});

		west = new JButton2(new ImageIcon("west.gif"), null, 75, 105);
		west.setEnabled(false);
		c.gridx = 0;
		c.gridy = 1;
		map_panel.add(west, c);
		west.addActionListener(new ActionListener(){

			public void actionPerformed(ActionEvent e) {
				
				//On v�rifie si on ne sors pas de la carte.
				if(map_x>0){
					map_x--;
					selected.width++;
					east.setEnabled(true);
				}
				
				//Si on arrive au bord de la carte, on d�sactive le bouton.
				if(map_x == 0) west.setEnabled(false);
				
				map_view.repaint();
			}
			
		});
		
/*CREATION MAP===>*/		
		try {
			initMap();
		} catch (RemoteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		map_view = new JPanel2("Y","C", 540, 540){
			
			private static final long serialVersionUID = 1L;
			Graphics2D g2D;			
			
			public void paintComponent(Graphics g){
				super.paintComponent(g);
				g2D = (Graphics2D) g;
				
				File village = new File("village.gif");
			    BufferedImage bufferedImage;
			    
			    //Taille des cases.
			    int size_x = 53;
			    int size_y = 53;
			    
			    //Espace par rapport au bord.
			    int space = 5;
				
			    try {
			    	//Chargement de l'image d'un village.
					bufferedImage = ImageIO.read(village);
					
					for(int i=0;i<10;i++)
					{
	 					for(int j=0;j<10;j++)
	 					{
	 						//debug.append(map_x + " " +map_y);
	 						
	 						//Quadrillage.
	 						if(selected.width == i & selected.height == j)
	 						{
	 							g2D.setColor(Color.red);
	 							g2D.drawRect(i*size_x+space-1,
	 										 j*size_y+space-1,
	 										 size_x-1,
	 										 size_y-1);
	 						}
	 						else{
	 							g2D.setColor(Color.black);
	 							g2D.drawRect(i*size_x+space-1,
										 	 j*size_y+space-1,
										 	 size_x-1,
										 	 size_y-1);
	 						}
	 						
	 						//Si la case contient un village, on le dessine.
	 						
	 						
	 						if(map.getVillage(i+map_x, j+map_y) instanceof Village){
	 							g2D.drawImage(bufferedImage, i*size_x+space, j*size_y+space, null);
	 						}	
	 					}
					}
				} catch (IOException e) {}
			}
		};
		map_view.setBackground(Color.white);
		c.gridx = 1;
		c.gridy = 1;
		map_panel.add(map_view, c);
		map_view.addMouseListener(new MouseListener(){
		
			public void mouseClicked(MouseEvent e) {
		
				//On rep�re les coordonn�es du click par rapport � la taille des cases.
				int x = (e.getX()/54);
				int y = (e.getY()/54);
				selected = new Dimension(x, y);
				
				//On fait coincider avec les emplacement relatif dans le tableau de la carte.
				int i = x+map_x;
				int j = y+map_y;
				
				Village vil=null;
				try {
					vil = map.getVillage(i, j);
				} catch (RemoteException e1) {}
				
				//Si c'est un village, on affiche ses informations.
				if(vil instanceof Village){
															
					//Onglet informations.
					player_name.setText( "Nom du joueur: " + vil.getPlayer());
					village_name.setText( "Nom du village: " + vil.getName());
					village_race.setText( "Race du joueur: " + vil.getRace());
						
					if(vil.getPlayer().equals(player)){
						
						infos_ressources.setVisible(true);
						options.setEnabledAt(1, true);
					    options.setEnabledAt(2, true);					
					    
						res_food.setText( "Food: " + vil.getCurFood()
												   + "/" + vil.getMaxFood()
												   + " +" + vil.getProdFood() + "/H");
						res_wood.setText( "Wood: " + vil.getCurWood()
												   + "/" + vil.getMaxWood()
												   + " +" + vil.getProdWood() + "/H");
						res_clay.setText( "Clay: " + vil.getCurSoil()
												   + "/" + vil.getMaxSoil()
												   + " +" + vil.getProdSoil() + "/H");
						res_iron.setText( "Iron: " + vil.getCurIron()
												   + "/" + vil.getMaxIron()
												   + " +" + vil.getProdIron() + "/H");
						
					}
					else{
						infos_ressources.setVisible(false);
						options.setEnabledAt(1, false);
					    options.setEnabledAt(2, false);
					}
					
					options.setSelectedIndex(0);
					options.setVisible(true);
				}
				else options.setVisible(false);
				
				map_view.repaint();
			}

			public void mouseEntered(MouseEvent arg0) {
				
			}

			public void mouseExited(MouseEvent arg0) {
				
			}

			public void mousePressed(MouseEvent arg0) {
				
			}

			public void mouseReleased(MouseEvent arg0) {
				
			}
		});
/*<===CREATION MAP*/
		
/*DIRECTION EST===>*/
		east = new JButton2(new ImageIcon("east.gif"), null, 75, 105);
		c.gridx = 2;
		c.gridy = 1;
		map_panel.add(east, c);
		east.addActionListener(new ActionListener(){

			public void actionPerformed(ActionEvent e) {
				
				//On v�rifie si on ne sors pas de la carte.
				if(map_x<map_size-10){
					map_x++;
					selected.width--;
					west.setEnabled(true);
				}
				
				//Si on arrive au bord de la carte, on d�sactive le bouton.
				if(map_x == map_size-10) east.setEnabled(false);
				
				map_view.repaint();
			}
			
		});
/*<===DIRECTION EST*/

/*DIRECTION SUD===>*/
		south = new JButton2(new ImageIcon("south.gif"), null, 105, 75);
		c.gridx = 1;
		c.gridy = 2;
		map_panel.add(south, c);	
		south.addActionListener(new ActionListener(){

			public void actionPerformed(ActionEvent e) {
				
				//On v�rifie si on ne sors pas de la carte.
				if(map_y<map_size-10){
					map_y++;
					selected.height--;
					north.setEnabled(true);
				}
				
				//Si on arrive au bord de la carte, on d�sactive le bouton.
				if(map_y == map_size-10) south.setEnabled(false);
				
				map_view.repaint();
			}
			
		});
/*<===DIRECTION SUD*/	
		
/* 
 * [1.2] Side View
*/
		JPanel side_view = new JPanel2("Y", "C", 300, 650);
		main.add(side_view);
		
/*INFORMATIONS DU VILLAGE===>*/
		infos = new JPanel2("Y", "C", 300, 600);
		
		JPanel2 infos_village = new JPanel2("Y","C",300,100);
		infos_village.setBorder(
				BorderFactory.createTitledBorder(
						BorderFactory.createLineBorder(Color.black, 2),
						" Informations: ")
				);
		infos.add(infos_village);
		
		player_name = new JLabel();
		infos_village.add(player_name);
		
		village_name = new JLabel();
		infos_village.add(village_name);
		
		village_race = new JLabel();
		infos_village.add(village_race);
		
		infos_ressources = new JPanel2("Y","C",300,120);
		infos_ressources.setBorder(
				BorderFactory.createTitledBorder(
						BorderFactory.createLineBorder(Color.black, 2),
						" Ressources: ")
				);
		infos.add(infos_ressources);
		
		res_food = new JLabel();
		infos_ressources.add(res_food);
		
		res_wood = new JLabel();
		infos_ressources.add(res_wood);
		
		res_clay = new JLabel();
		infos_ressources.add(res_clay);
		
		res_iron = new JLabel();
		infos_ressources.add(res_iron);
/*<===INFORMATIONS DU VILLAGE*/
		
/*BATIMENTS DU VILLAGE===>*/		
		
		build_panel = new JPanel2("Y", "C", 300, 600);
		
		JPanel2 build_choice = new JPanel2("X","L", 300, 100);
		build_choice.setBorder(
				BorderFactory.createTitledBorder(
						BorderFactory.createLineBorder(Color.black, 2),
						" Choix du batiment: ")
				);
		
		String[] buildings = {"Hotel de ville",
				  "Ferme", "Bucheron", "Tailleur", "Mineur",
				  "Silo", "Entrepot",
				  "Caserne", "Ecurie"};
		
		build_list = new JComboBox(buildings);
		build_list.setSelectedItem(null);
		build_list.setPreferredSize(new Dimension(100,20));
		build_list.setMaximumSize(new Dimension(100,20));
		build_list.setMinimumSize(new Dimension(100,20));					
		build_choice.add(build_list);
		build_list.addActionListener(new ActionListener(){

			public void actionPerformed(ActionEvent arg0) {
				
				int selection = build_list.getSelectedIndex();
				
				switch (selection){
					case 0: building_image = "town_hall.gif";
					break;
					case 1: building_image = "farm.gif";
					break;
					case 2: building_image = "sawmill.gif";
					break;
					case 3: building_image = "stonecutter.gif";
					break;
					case 4: building_image = "miner.gif";
					break;
					case 5: building_image = "storage.gif";
					break;
					case 6: building_image = "granary.gif";
					break;
					case 7: building_image = "barracks.gif";
					break;
					case 8: building_image = "stable.gif";
					break;
				}
				
				Village vil=null;
				try {
					vil = map.getVillage(selected.width+map_x, selected.height+map_y);
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				String buildingName   = vil.getBuilding(selection).getType().name();
				String buildingStatus = vil.getBuilding(selection).getStatus();
				int buildingLevel     = vil.getBuilding(selection).getLevel();
						
				if(buildingStatus.equals("Non construit")){
					build_button.setEnabled(true);
					upgrade_button.setEnabled(false);
				}
				else if(buildingStatus.equals("Construit")){
					build_button.setEnabled(false);
					upgrade_button.setEnabled(true);
				}
				else if(buildingStatus.equals("En Construction")){
					build_button.setEnabled(false);
					upgrade_button.setEnabled(false);
				}
								    
				build_name.setText("Nom: " + buildingName);
				build_status.setText("Status: " + buildingStatus);
				build_level.setText("Level: " + buildingLevel);
				
				build_infos.setVisible(true);
				build_actions.setVisible(true);
				
				build_pic.repaint();
			}			
		});					
		
		building_image = "village.gif";
		
		build_pic = new JPanel(){

			private static final long serialVersionUID = 1L;
			File file; 						
			
			public void paintComponent(Graphics g) {
				
				file = new File(building_image);
				
				try{
					BufferedImage image = ImageIO.read(file);
					g.drawImage(image,50,0,this);
				} catch (IOException e) {}
				
			}
		};
		build_choice.add(build_pic);
		
		build_panel.add(build_choice);
		
		build_infos = new JPanel2("Y","L", 300, 100);
		build_infos.setVisible(false);
		build_infos.setBorder(
				BorderFactory.createTitledBorder(
						BorderFactory.createLineBorder(Color.black, 2),
						" Informations: ")
				);
		
		build_name = new JLabel();
		build_infos.add(build_name);
		
		build_status = new JLabel();
		build_infos.add(build_status);
		
		build_level = new JLabel();
		build_infos.add(build_level);
		
		build_panel.add(build_infos);
		
		build_actions = new JPanel2("Y","L", 300, 150);
		build_actions.setVisible(false);
		build_actions.setBorder(
				BorderFactory.createTitledBorder(
						BorderFactory.createLineBorder(Color.black, 2),
						" Actions: ")
				);
		
		JPanel2 action_build = new JPanel2("X","L",300,35);
		build_actions.add(action_build);
		JLabel action_build_label = new JLabel("Construire -> ");
		action_build.add(action_build_label);
		build_button = new JButton2(new ImageIcon("build.gif"), null, 30, 30);
		build_button.addActionListener(new ActionListener(){

			public void actionPerformed(ActionEvent arg0) {
			
				
			
			}			
		});
		action_build.add(build_button);
		
		build_cost = new JLabel("Cout: 100 200 110 220");
		build_actions.add(build_cost);
		
		build_actions.add(new JSeparator());
		
		JPanel2 action_upgrade = new JPanel2("X","L",300,35);
		build_actions.add(action_upgrade);
		JLabel action_upgrade_label = new JLabel("Am�liorer -> ");
		action_upgrade.add(action_upgrade_label);
		upgrade_button = new JButton2(new ImageIcon("upgrade.gif"), null, 30, 30);
		upgrade_button.addActionListener(new ActionListener(){

			public void actionPerformed(ActionEvent arg0) {
			
				
			
			}			
		});
		action_upgrade.add(upgrade_button);		
		
		upgrade_cost = new JLabel("Cout: 300 410 210 520");
		build_actions.add(upgrade_cost);
		
		build_panel.add(build_actions);
/*<===BATIMENTS DU VILLAGE*/
		
		milit_panel = new JPanel();
		
		options = new JTabbedPane(JTabbedPane.TOP);
		options.setVisible(false);
		
		options.addTab("Informations", infos);		
		options.addTab("Batiments", build_panel);
		options.addTab("Armée", milit_panel);
		side_view.add(options);
		
		frame.setVisible(true);
	}
}
